package com.smy.baseutil.config.dynamic;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

@SuppressWarnings("unchecked")
public class ReloadablePropertiesBase extends DelegatingProperties implements ReloadableProperties {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private List<IReloadablePropertiesListener> listeners = new ArrayList<>();
	private Properties internalProperties;
	
    public void setListeners(List<IReloadablePropertiesListener> listeners) {
        this.listeners = listeners;
    }

	@Override
	public Properties getProperties() {
		 return getDelegate();
	}

	@Override
	public void addReloadablePropertiesListener(IReloadablePropertiesListener l) {
		listeners.add(l);

	}

	@Override
	public boolean removeReloadablePropertiesListener(IReloadablePropertiesListener l) {
		return listeners.remove(l);
	}

	@Override
	protected Properties getDelegate() {
		 synchronized(this) {
	            return internalProperties;
	        }
	}
	
	  /**
     * 通过listener去通知 reload
     *
     * @param oldProperties
     */
    protected void notifyPropertiesChanged(Properties oldProperties) {
        PropertiesReloadedEvent event = new PropertiesReloadedEvent(this, oldProperties);
        for (IReloadablePropertiesListener listener : listeners) {
            listener.propertiesReloaded(event);
        }
    }

    /**
     * set value 触发
     *
     * @param properties
     */
    public void setProperties(Properties properties) {
        Properties oldProperties = internalProperties;
        synchronized(this) {
            internalProperties = properties;
        }
        notifyPropertiesChanged(oldProperties);
    }

}
